
//529.扫雷游戏
class Solution {
public:
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        int dx[]={-1,1,1,1,-1,-1,0,0};  
        int dy[]={0,0,1,-1,1,-1,-1,1};
        int n=board.size(),m=board[0].size(),count;
        function<int(int,int)> mine_count=[&](int x,int y)  //计算周围雷的个数
        {
            int ret=0;
            for(int k=0;k<8;k++)
            {
                int a=x+dx[k],b=y+dy[k];
                if(a>=0&&a<n&&b>=0&&b<m&&board[a][b]=='M') ret++;
            } 
            return ret;
        };
        function<void(int,int)> dfs=[&](int x,int y)
        {
            int count=mine_count(x,y);
            if(count)    board[x][y]='0'+count;  //周围有雷
            else   //作为没有雷
            {
                board[x][y]='B';
                for(int k=0;k<8;k++)
                {
                    int a=x+dx[k],b=y+dy[k];
                    if(a>=0&&a<n&&b>=0&&b<m&&board[a][b]=='E') dfs(a,b);
                }
            }
        };
        if(board[click[0]][click[1]]=='M')  board[click[0]][click[1]]='X';  //是雷
        else  dfs(click[0],click[1]);   //不是雷
        return board;
    }
};